package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service("sellerService")
public class SellerServiceImpl implements SellerService {
    @Autowired
    SellerMapper sellerMapper;

    @Autowired
    HttpSession session;

    //注册
    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        seller.setPassword(MD5Coder.md5Encode(seller.getPassword()));
        int flag = sellerMapper.insert(seller);
        return flag>0;
    }

    //登录
    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        SellerExample example = new SellerExample();
        example.createCriteria()
                .andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        List<Seller> sellers = sellerMapper.selectByExample(example);
        List<SellerVo> sellerVos = BeanConv.toBeanList(sellers, SellerVo.class);
        if (sellerVos.size()==0){
            return null;
        }
        SellerVo sellerVoResult = sellerVos.get(0);
        String sessionId = session.getId();
        sellerVoResult.setSessionId(sessionId);
        session.setAttribute(sessionId,sellerVoResult);
        return sellerVoResult;
    }

    //退出
    @Override
    public void loginOutSeller() {
        session.removeAttribute(session.getId());
    }

    //是否登录
    @Override
    public Boolean isLogin() {
        return EmptyUtil.isNullOrEmpty(
                session.getAttribute(session.getId())
        );
    }

    //通过id查找
    @Override
    public SellerVo findSellerVoById(SellerVo sellerVo) {
        /*Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        SellerExample example = new SellerExample();

        example.createCriteria()
                .andIdEqualTo(seller.getId());
        List<Seller> sellers = sellerMapper.selectByExample(example);
        if (sellers.size()==0) {
            return null;
        }
        return sellerVo;*/

        return BeanConv.toBean(
                sellerMapper.selectByPrimaryKey(sellerVo.getId()),
                SellerVo.class
        );
    }
}
